<template>
  <view class="phxx-item">
    <view class="phxx-item-content" @click="goToDetail(itemList)">
      <view class="top">
        <view class="cname-box">
          <view class="cname" v-if="goodsType == 'deliver'">{{
            itemList.purchase || itemList.enterName || ''
            }}</view>
          <view class="cname" v-else>{{ itemList.cusName || '' }}</view>
          <view class="cname-fu-box">
            <view class="cname-fu">
              <text class="">{{ itemList.proName || '' }}</text>
            </view>
            <view v-if="goodsType == 'deliver' && itemList.freightRate" class="line"></view>
            <view class="cname-fu" v-if="goodsType == 'deliver'">
              <text v-show="itemList.freightRate" class="val">{{ itemList.freightRate }}元/吨</text>
            </view>
          </view>
        </view>
        <view v-if="goodsType == 'deliver'" :class="{
            'gray-type': itemList.status == 8 || itemList.status == 9,
            'orange-type': itemList.status == 0 || itemList.status == 1,
            'blue-type': itemList.status >= 2 && itemList.status <= 6,
            'green-type': itemList.status == 7,
            'red-type': itemList.status == 10,
            status: true
          }">{{ statusListsPurch[itemList.status].text }}</view>
        <view v-else :class="{
            'gray-type': itemList.status == 7 || itemList.status == 8,
            'orange-type': itemList.status == 0,
            'blue-type': itemList.status >= 1 && itemList.status <= 5,
            'green-type': itemList.status == 6,
            status: true
          }">{{ statusListsSale[itemList.status].text }}</view>
      </view>

      <view class="body-box no-back">
        <view class="bottom">
          <view class="items full">
            <text class="til col66">车牌号:</text>
            <view class="val col3 carNoBox">
              <view>{{ itemList.carBrand || '' }}</view>
              <view v-if="isShowWeightSlip" class="global-color-text" @click="linkToReceipt(itemList.id)">查看磅单</view>
            </view>
          </view>
        </view>

        <view class="bottom" v-if="goodsType == 'deliver'">
          <view class="items full">
            <text class="til col66">承运单位:</text>
            <text class="val col3">{{ itemList.cusTransport || '' }}</text>
          </view>
        </view>
        <view class="bottom" v-if="goodsType == 'deliver'">
          <view class="items full">
            <text class="til col66">卸货点:</text>
            <text class="val col3">{{ itemList.landingPointName || '' }}</text>
          </view>
        </view>
        <view class="bottom" v-if="goodsType == 'pull'">
          <view class="items">
            <text class="til col66">车辆类型:</text>
            <text class="val col3">{{ itemList.modelId || '' }}</text>
          </view>
        </view>
        <view class="bottom" v-if="goodsType == 'pull'">
          <view class="items full">
            <text class="til col66">联系人电话:</text>
            <text class="val col3">{{ itemList.cusPhone || '' }}</text>
          </view>
        </view>

        <view class="bottom" v-if="goodsType == 'pull'">
          <view class="items full">
            <text class="til col66">姓名:</text>
            <text class="val col3">{{ itemList.carName || '' }}</text>
          </view>
        </view>
        <view class="bottom" v-if="goodsType == 'pull'">
          <view class="items full">
            <text class="til col66">身份证号:</text>
            <text class="val col3">{{ itemList.carCard || '' }}</text>
          </view>
        </view>
        <view class="bottom" v-if="goodsType == 'pull'">
          <view class="items full">
            <text class="til col66">司机电话:</text>
            <text class="val col3">{{ itemList.carPhone || '' }}</text>
          </view>
        </view>
      </view>
      <view class="bottom gray-items" v-if="goodsType == 'deliver'">
        <view class="items title" style="">
          <text class="tils blue">矿发:</text>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">毛重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.mineralGrossWeight || '-'
            }}</view>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">皮重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.mineralTareWeight || '-'
            }}</view>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">净重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.mineralNetWeight || '-'
            }}</view>
        </view>
      </view>

      <view class="bottom gray-items" v-if="goodsType == 'deliver'">
        <view class="items title">
          <text class="tils red">到站:</text>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">毛重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.grossWeight || '-'
            }}</view>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">皮重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.netWeight || '-'
            }}</view>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">净重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.totalWeight || '-'
            }}</view>
        </view>
      </view>

      <view class="bottom gray-items" v-if="goodsType == 'pull'">
        <view class="items title" style="">
          <text class="tils red">到站:</text>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">皮重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.netWeight || '-'
            }}</view>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">净重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.totalWeight || '-'
            }}</view>
        </view>
        <view class="items num-box font14">
          <view class="til col99 font13">毛重:</view>
          <view class="val col00 font16 fontwtb">{{
            itemList.grossWeight || '-'
            }}</view>
        </view>
      </view>
      <view v-if="goodsType == 'deliver'">
        <span style="font-size: 14px;color:red;display: block;"
          v-if="(itemList.waybillRemark) && (itemList.waybillUpload === 2 || itemList.waybillUpload === 4 || itemList.waybillUpload === 6 || itemList.waybillUpload === 8)">
          失败原因: {{itemList.waybillRemark}}</span>
        <span style="font-size: 14px;color: #ff8800;display: block;"
          v-if="(itemList.waybillRemark) && (itemList.waybillUpload === 2 || itemList.waybillUpload === 4 || itemList.waybillUpload === 6 || itemList.waybillUpload === 8)">
          注意: 网货上传失败会影响运费结算{{number}}</span>
      </view>
    </view>
    <view class="button-container">
      <button
        v-if="itemList.waybillUpload === 2 || itemList.waybillUpload === 4 || itemList.waybillUpload === 6 || itemList.waybillUpload === 8"
        class="button customButton" type="warn" plain="true" @click.stop="openReupload(itemList)">
        重新上传
      </button>
      <view class="bottom-btn" v-if="itemList.lineupSwitch === 0" style="flex: 1; margin: 0 5px;">
        <view class="btn">
          <button class="btn small-size" type="primary" size="default" @click="goToLine()" style="width: 100%;">
            排号
          </button>
        </view>
      </view>
      <view class="bottom-btn" v-if="itemList.saleLineupSwitch === 0" style="flex: 1; margin: 0 5px;">
        <view class="btn">
          <button class="btn small-size" type="primary" size="default" @click="goToLine()" style="width: 100%;">
            排号
          </button>
        </view>
      </view>
      <view class="bottom-btn" v-if="itemList.status == '0' && goodsType == 'pull'" style="flex: 1; margin: 0 5px;">
        <view class="btn">
          <button class="btn small-size" type="danger" size="default" @click="cancelOrder()" :disabled="loading"
            style="width: 100%;">
            取消订单
          </button>
        </view>
      </view>
      <view class="bottom-btn" v-if="itemList.statusType == '0' && goodsType == 'deliver'"
        style="flex: 1; margin: 0 5px;">
        <view class="btn">
          <button class="btn small-size" type="danger" size="default" @click="cancelPurOrder()" :disabled="isLoading"
            style="width: 100%;">
            取消订单
          </button>
        </view>
      </view>
    </view>
    <!-- 重新上传弹窗 -->
    <uni-popup ref="popupReupload">
      <view class="pop violation-pop">
        <view class="popxx-itemss">
          <view class="header">
            <view class="title">重新上传</view>
          </view>
          <view class="top calling">
            <view style="padding: 15px">
              <view class="title"
                style="padding-bottom: 5px;display: flex; justify-content: space-between; align-items: center;">
                <span style="color:red;">*</span>收款方式
                <span style="font-size: 26.66rpx; color: #0088ff; margin-left: auto; cursor: pointer;"
                  @click="updataDataClick(itemList)">
                  <uni-icons type="loop" size="16" color="#0088ff" />
                  更新收款信息</span>
              </view>
              <uni-data-select v-if="showSelect" v-model="receiptValue" :localdata="receiptRange"
                @change="receiptChange"></uni-data-select>
            </view>
            <view style="padding: 15px;">
              <view class="title" style="padding-bottom: 5px" v-if="backShow"><span style="color:red;">*</span>收款银行卡
              </view>
              <view class="title" style="padding-bottom: 5px" v-else><span style="color:red;">*</span>收款账户</view>
              <uni-data-select v-if="showSelect" v-model="accountValue" :localdata="balanceOrBankRange"
                @change="balanceOrBankChange"></uni-data-select>
            </view>
          </view>
          <view class="btn">
            <button class="mini-btn" @click="close('popupReupload')" type="primary" plain="true" size="mini">
              取消
            </button>
            <button class="mini-btn" @click="confirmReupload()" type="primary" plain="true" size="mini"
              :class="{ loading: isLoadingFlag }">
              确定
            </button>
          </view>
        </view>
      </view>
    </uni-popup>
    <tip-box :show="showBlacklistTip" :message="blacklistTip" :duration="8000" @showTip="showTip"></tip-box>
  </view>
</template>

<script>
  import config from '@/config';
  import { cancelOrderApi, cancelPurOrderApi, syncNetGoodsByDriver } from '@/api/system/goods.js';
  import { toast, dictTansParams } from '@/utils/common.js';
  import { getDictDatas, getPayeeInfoLists } from '@/api/me.js';
  export default {
    name: 'goods-number',
    props: {
      goodsType: {
        type: String
      },
      tenantId: {
        type: Number
      },
      itemList: {
        type: Object,
        default: {
          purchase: '',
          enterName: '',
          status: '',
          supName: '',
          carBrand: '',
          proName: '',
          freightRate: '',
          loadingPoint: '',
          mineralTareWeight: '',
          mineralNetWeight: '',
          netWeight: '',
          totalWeight: ''
        }
      }
    },
    data() {
      return {
        showSelect: false,
        showBlacklistTip: false,
        blacklistTip: '',
        backShow: false,
        receiptValue: undefined,
        accountName: undefined,
        accountValue: undefined,
        receiptRange: [],
        balanceAccountRange: [],
        balanceOrBankRange: [],
        number: '',
        loading: false,
        isLoading: false,
        isLoadingFlag: false,
        statusListsSale: [
          {
            id: 0,
            text: '待审核'
          },
          {
            id: 1,
            text: '待入场'
          },
          {
            id: 2,
            text: '待录皮'
          },
          {
            id: 3,
            text: '待装煤'
          },
          {
            id: 4,
            text: '待称毛'
          },
          {
            id: 5,
            text: '待出厂'
          },
          {
            id: 6,
            text: '已完成'
          },
          {
            id: 7,
            text: '已作废'
          },
          {
            id: 8,
            text: '已终止'
          }
        ],
        statusListsPurch: [
          {
            id: 0,
            text: '待供应商审核'
          },
          {
            id: 1,
            text: '待采购方审核'
          },
          {
            id: 2,
            text: '待入场'
          },
          {
            id: 3,
            text: '待称毛'
          },
          {
            id: 4,
            text: '待确认'
          },
          {
            id: 5,
            text: '待录皮'
          },
          {
            id: 6,
            text: '待出厂'
          },
          {
            id: 7,
            text: '已完成'
          },
          {
            id: 8,
            text: '已作废'
          },
          {
            id: 9,
            text: '已终止'
          },
          {
            id: 10,
            text: '挂起'
          }
        ],
        payeeInfoParam: {
          goodsId: undefined,
          vehicleNo: undefined,
          networkFreight: undefined,
        },
        syncNetGoodsByDriverParam: {
          waybillId: undefined,
          freightCollectionAccountId: undefined,
          freightCollectionType: undefined,
          freightCollectionAccount: undefined,
        },
      };
    },
    computed: {
      isShowWeightSlip() {
        return this.goodsType == 'pull' && this.itemList.status == 6 && config.viewBDOwers.includes(this.tenantId)
      }
    },
    onLaunch() {
      console.log(this.goodsType);
    },
    methods: {
      async openReupload(itemList) {
        if (itemList.waybillUpload === 2 || itemList.waybillUpload === 4) {
          this.showSelect = true
          this.$refs['popupReupload'].open('bottom');
          await this.getReceiptTypeList(itemList)
          this.receiptValue = String(itemList.freightCollectionType)
          if (this.receiptValue === '1') {
            this.balanceOrBankRange = this.bankCardAccountRange.map(item => ({
              value: item.id,
              text: item.value
            }));
            this.backShow = true
          }
          if (this.receiptValue === '2') {
            this.balanceOrBankRange = this.balanceAccountRange.map(item => ({
              value: item.id,
              text: item.value
            }));
            this.backShow = false
          }
          this.accountName = itemList.freightCollectionAccount
          this.accountValue = String(itemList.freightCollectionAccountId)

          this.syncNetGoodsByDriverParam.waybillId = itemList.id
        } else if (itemList.waybillUpload === 6 || itemList.waybillUpload === 8) {
          const that = this;
          uni.showModal({
            title: '重新上传',
            content: "您确认信息已修改正确吗？",
            success: async function (res) {
              if (res.confirm) {
                let data = {
                  waybillId: itemList.id
                }
                wx.showLoading({
                  title: '正在提交...',
                  mask: true
                });
                try {
                  let res = await syncNetGoodsByDriver(data);
                  if (res.code == 0) {
                    wx.hideLoading()
                    toast(`重新上传成功`);
                  } else {
                    wx.hideLoading()
                    that.blacklistTip = res.msg
                    that.showBlacklistTip = true
                  }
                } catch (error) {
                  console.error("上传请求出错:", error);
                  toast(`重新上传失败`);
                } finally {
                  that.$emit('getLists');
                }
              }
            }
          })
        }
      },
      close(ref) {
        this.$refs[ref].close();
        this.showSelect = false
      },
      //重新上传
      async confirmReupload() {
        if (this.isLoadingFlag) return;
        this.syncNetGoodsByDriverParam.freightCollectionType = this.receiptValue
        this.syncNetGoodsByDriverParam.freightCollectionAccountId = this.accountValue
        this.syncNetGoodsByDriverParam.freightCollectionAccount = this.accountName
        if (!this.syncNetGoodsByDriverParam.freightCollectionType) {
          toast(`请选择收款方式`);
          return;
        }
        if (!this.syncNetGoodsByDriverParam.freightCollectionAccountId && !this.backShow) {
          toast(`请选择收款账户`);
          return;
        } else if (!this.syncNetGoodsByDriverParam.freightCollectionAccountId && this.backShow) {
          toast(`请选择收款银行卡`);
          return;
        }
        this.isLoadingFlag = true
        wx.showLoading({
          title: '正在提交...',
          mask: true
        });
        this.$refs['popupReupload'].close();
        try {
          let res = await syncNetGoodsByDriver(this.syncNetGoodsByDriverParam);
          if (res.code == 0) {
            wx.hideLoading()
            toast(`重新上传成功`);
          } else {
            wx.hideLoading()
            this.blacklistTip = res.msg
            this.showBlacklistTip = true
          }
        } catch (e) {
          wx.hideLoading()
          toast(`重新上传失败`);
          console.error("上传请求出错:", e);
        } finally {
          this.$emit('getLists');
          this.showSelect = false
          this.isLoadingFlag = false
        }
      },
      updataDataClick(itemList) {
        console.log('获取最新收款信息');
        this.getReceiptTypeList(itemList)
        if (this.msgStatus) {
          toast('更新成功')
        }
      },
      async getDictLists() {
        let datas = await getDictDatas();
        let res = await dictTansParams(datas.data, 'freight_collection_type');
        this.receiptRange = res.map((item) => {
          return {
            value: item.value,
            text: item.text
          };
        });
      },
      //获取收款方式和收款账户列表
      async getReceiptTypeList(itemList) {
        this.payeeInfoParam.vehicleNo = itemList.carBrand
        this.payeeInfoParam.goodsId = itemList.goodsId
        this.payeeInfoParam.networkFreight = itemList.networkFreight
        await this.getDictLists()
        this.bankCardAccountRange = []
        this.balanceAccountRange = []
        try {
          let res = await getPayeeInfoLists(this.payeeInfoParam);
          if (res.code == 0) {
            if (res.data.length > 0) {
              res.data.forEach(item => {
                if (item.code === "1") { // 如果是银行卡类型
                  item.items.forEach(bankItem => {
                    this.bankCardAccountRange.push({
                      id: bankItem.id,
                      userId: bankItem.userId,
                      value: bankItem.value,
                    });
                  });
                } else if (item.code === "2") { // 如果是余额类型
                  item.items.forEach(balanceItem => {
                    this.balanceAccountRange.push({
                      id: balanceItem.id,
                      userId: balanceItem.userId,
                      value: balanceItem.value,
                    });
                  });
                }
              });
              this.msgStatus = true
            }
          } else if (res.code == 100419999) {
            this.msgStatus = true
          } else {
            toast(`${res.msg}`);
            this.msgStatus = false
          }
        } catch (e) {
          this.msgStatus = false
          return false;
        }
      },

      receiptChange(e) {
        this.balanceOrBankRange = []
        if (e === '1') {
          this.balanceOrBankRange = this.bankCardAccountRange.map(item => ({
            value: item.id,
            text: item.value
          }));
          this.receiptValue = ''
          this.accountValue = ''
          this.accountName = ''
          this.backShow = true
        } else if (e === '2') {
          this.balanceOrBankRange = this.balanceAccountRange.map(item => ({
            value: item.id,
            text: item.value
          }));
          this.receiptValue = ''
          this.accountValue = ''
          this.accountName = ''
          this.backShow = false
        } else {
          this.receiptValue = ''
          this.accountValue = ''
          this.accountName = ''
          this.backShow = false
        }
      },
      balanceOrBankChange(e) {
        this.balanceOrBankRange.forEach(item => {
          if (item.value == e) {
            this.accountName = item.text
          }
        });
      },
      goToLine() {
        if (this.goodsType === 'deliver') {
          uni.setStorageSync('orderType', 1);
        } else {
          uni.setStorageSync('orderType', 2);
        }
        this.$tab.reLaunch('/pages/index?lineup=1');
      },
      //销售取消运单
      async cancelOrder() {
        this.loading = true;
        try {
          let res = await cancelOrderApi({ id: this.itemList.id });
          if (res.code == 200) {
            toast(`取消订单成功`);
            this.$emit('getLists');
          } else {
            toast(res.message);
            this.$emit('getLists');
          }
        } catch (error) {
          toast(`取消订单失败`);
        } finally {
          this.loading = false;
        }
      },
      //采购取消运单
      async cancelPurOrder() {
        this.isLoading = true;
        try {
          let res = await cancelPurOrderApi(this.itemList.id);
          if (res.code == 200) {
            toast(`取消订单成功`);
            this.$emit('getLists');
          } else {
            toast(res.message);
            this.$emit('getLists');
          }
        } catch (error) {
          toast(`取消订单失败`);
        } finally {
          this.isLoading = false;
        }
      },
      goToDetail(item) {
        if (this.goodsType == 'deliver') {
          uni.navigateTo({
            url: `/packageA/pages/work/deliverGoods/details?id=${item.id}`
          });
        }
        // if (this.goodsType == 'pull') {
        //   uni.navigateTo({
        //     url: `/packageA/pages/work/pullGoods/details?id=${item.id}`
        //   });
        // }
      },
      linkToReceipt(id) {
        uni.navigateTo({
          url: `/packageA/pages/work/receipt/index?id=${id}`
        });
      },
      closePopupReupload() {
        this.$refs['popupReupload'].close();
        this.showSelect = false
      },
      showTip(event) {
        this.showBlacklistTip = event
      }
    }
  };
</script>

<style lang="scss" scoped>
  .customButton {
    font-size: 28rpx !important;
    background: white !important;
    color: #ff0000 !important;
    height: 60rpx !important;
    line-height: 60rpx !important;
    border: 1px solid !important;
    flex: 1;
    margin: 0 5px;
  }

  .carNoBox {
    display: flex;
    justify-content: space-between;
    flex: 1
  }

  .button-container {
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
    padding-bottom: 10px;
    align-items: center;
  }

  .button-container .bottom-btn {
    margin-left: 10px;
    /* 可根据需要调整按钮之间的间距 */
  }
</style>